/**
 * 
 */
package leetCode;

/**
 * @author zhongfang
 *
 */
public class StringCompression {
	/**
	 * 压缩后的长度
	 * 
	 * @param chars
	 * @return
	 */
	public int compress(char[] chars) {
		if (chars.length < 2) {
			return chars.length;
		}
		int len = 0;
		int count = 0;
		int curPos = 0;
		for (int i = 0; i < chars.length; i++) {
			if (i == 0 || chars[i] == chars[i - 1]) {
				count++;
			} else {
				len++;
				chars[curPos++] = chars[i - 1];
				if (count != 1) {
					String intCount = String.valueOf(count);
					len += intCount.length();
					for (int j = 0; j < intCount.length(); j++) {
						chars[curPos++] = intCount.charAt(j);
					}
				}
				count = 1;
			}
		}
		len++;
		chars[curPos++] = chars[chars.length - 1];
		if (count != 1) {
			String intCount = String.valueOf(count);
			len += intCount.length();
			for (int j = 0; j < intCount.length(); j++) {
				chars[curPos++] = intCount.charAt(j);
			}
		}
		return len;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		char[] chars = { 'a', 'a', 'b', 'b', 'c', 'c', 'c' };
		System.out.println(new StringCompression().compress(chars));
		System.out.println(chars);
	}

}
